from telegram import InlineKeyboardButton, InlineKeyboardMarkup,ReplyKeyboardMarkup,KeyboardButton
from datetime import datetime, timedelta
# 创建机器人开始命令

def creatOptions(strList:list,aim:str,data:dict):
    if not strList:raise ValueError('不能为空')
    keyboard = []
    for item in strList:
        keyboard.append(
            InlineKeyboardButton(item,callback_data="%s %d+courseStatus"%(formatted_date,index)),#
        )
        
    # 创建键盘标记（resize_keyboard 调整键盘大小，one_time_keyboard 发送后隐藏）
    start_reply_markup = ReplyKeyboardMarkup(
        [keyboard], 
        resize_keyboard=True,
        one_time_keyboard=False  # 设置为 True 可在用户点击后隐藏键盘
    )
    return InlineKeyboardMarkup()

def creatCourseMsg(courseList:list):
    ''''''
    pass
time_intervals = [f"{h:02d}:00-{h%24+1:02d}:00" for h in range(24)]
courseStatusList=['休息','开放预约','有申请','已确认']
def createTimeIntervalsKeyboard(teacherObj,time_intervals=time_intervals):
    '''用于创建老师的预约课表，老师可做多种修改'''
    now = datetime.now()
    keyboard=[]
    thisHourNum=int(now.hour)
    if teacherObj['displayToday']==0:
        course24=teacherObj['day0']
        month,day=tuple(teacherObj['date0'].split('-'))
        formatted_date_sim = "%s月%s日"%(month,day)
        formatted_date = teacherObj['date0'] # 07月05日
    else:
        course24=teacherObj['day1']
        month,day=tuple(teacherObj['date1'].split('-'))
        formatted_date_sim = "%s月%s日"%(month,day)
        formatted_date = teacherObj['date1'] # 07月05日
    keyboard.append([InlineKeyboardButton(formatted_date_sim,callback_data=formatted_date)])
    for index,Code in enumerate(course24):
        statusCode=int(Code)
        if statusCode==0 and teacherObj['hideRest'] ==1 :continue  #隐藏休息时段
        if index<thisHourNum and teacherObj['displayToday']==0:continue   #今天意见过去的时段，不显示
        peroid=time_intervals[index]
        button2=InlineKeyboardButton('',callback_data="%s %d+courseStatus"%(formatted_date,index)),#
        if statusCode==0:
            statusMsg='休息'
        elif statusCode==1:
            statusMsg='可预约'
        elif statusCode==2:
            num=0
            for item in teacherObj['bookedCourseList']:
                if all([
                    formatted_date==item['date'],
                    index==int(item['peroidIndex']),
                    item['status']==0
                ]):
                    num=num+1
            statusMsg='%d人已预约'%num
        elif statusCode==3:  #0代表休息  1代表开放预约 2代表有申请未确认 3代表已确认申请 4代表预约已过期
            statusMsg='未找到预约用户'
            for item in teacherObj['bookedCourseList']:
                if all([
                    formatted_date==item['date'],
                    index==item['peroidIndex'],
                    item['status']==1
                ]):
                    statusMsg='@'+item['student']
                
        elif statusCode==4:
            statusMsg='已过期'
        keyboard.append([                        #callback_data不能为空
            InlineKeyboardButton(peroid,callback_data="%s %d"%(formatted_date,index)),
            InlineKeyboardButton(statusMsg,callback_data="%d %s %d+courseStatus"%(statusCode,formatted_date,index)),
            # InlineKeyboardButton(text='设置',callback_data="%s %d+moreSetting"%(formatted_date,index))
        ])
    
    hideRestButtonText='显示' if teacherObj['hideRest'] else "隐藏"
    keyboard.append([
            InlineKeyboardButton(text='%s休息时段'%hideRestButtonText,callback_data='hideRest'),
            InlineKeyboardButton(text='保存设置',callback_data='saveSetting'),
            InlineKeyboardButton(text='今/明天课表',callback_data='today/tomorrow+teacher+%s'%teacherObj['nickname'])
            ])
    keyboard.append([
            InlineKeyboardButton(text='设为全休',callback_data='allRest'),
            InlineKeyboardButton(text='刷新课表',callback_data='refresh'),
            InlineKeyboardButton(text='课表地址',callback_data='CourseUrl'),
            ])
    return InlineKeyboardMarkup(keyboard)

def istoCreateCourse(nickname):
    '''用于创建初次进入的老师，确认创建课表'''
    keyboard=[]
    keyboard.append([
            InlineKeyboardButton(text='点击创建初始课表',callback_data='%s+createNewCourse'%nickname),
            ])
    return InlineKeyboardMarkup(keyboard)

def createStudentCourse(studentObj,teacherObj,time_intervals=time_intervals):
    '''用于创建学生视角下的老师的预约课表'''
    now = datetime.now()
    keyboard=[]
    thisHourNum=int(now.hour)
    courseStatusList=['休息','可预约','有申请','已占用']
    if studentObj['displayToday']==0:
        course24=teacherObj['day0'].zfill(24)
        month,day=tuple(teacherObj['date0'].split('-'))
        formatted_date_sim = "%s月%s日"%(month,day)
        formatted_date = teacherObj['date0'] # 07月05日
    else:
        course24=teacherObj['day1'].zfill(24)
        month,day=tuple(teacherObj['date1'].split('-'))
        formatted_date_sim = "%s月%s日"%(month,day)
        formatted_date = teacherObj['date1'] # 07月05日
    keyboard.append([InlineKeyboardButton(formatted_date_sim,callback_data=formatted_date)])
    for index,Code in enumerate(course24):
        statusCode=int(Code)
        if statusCode==0 and studentObj['hideRest'] ==1 :continue  #隐藏休息时段
        if index<thisHourNum and studentObj['displayToday']==0:continue   #今天意见过去的时段，不显示
        peroid=time_intervals[index]
        #0代表休息  1代表开放预约 2代表有申请未确认 3代表已确认申请 4代表预约已过期
        if statusCode==0:
            statusMsg='休息不可约'

        elif statusCode==1:
            statusMsg='可预约'
        elif statusCode==2:
            num=0
            for item in teacherObj['bookedCourseList']:
                if all([
                    formatted_date==item['date'],
                    index==int(item['peroidIndex']),
                    item['status']==0
                ]):
                    num=num+1
            statusMsg='%d人已预约'%num
        elif statusCode==3:
            ls=list(filter(lambda T:T['date']==formatted_date and int(T['peroidIndex'])==index and T['status']==1,teacherObj['bookedCourseList']))
            if len(ls)==1:
                if ls[0]['student']==studentObj['nickname']:
                    statusMsg='您已预约'
                else:
                    statusMsg='休息不可约'  #保护老师隐私，已被他人占用的时段，显示休息，防止学生知道老师课程多少
            else:
                statusMsg='数据异常'
        elif statusCode==4:
            statusMsg='已过期'
        keyboard.append([                        #callback_data不能为空
            InlineKeyboardButton(peroid,callback_data="%s %d"%(formatted_date,index)),
            InlineKeyboardButton(statusMsg,callback_data="%s %d+courseSTD_status"%(formatted_date,index)),#
            InlineKeyboardButton(text='预约',callback_data="%s %d %d %s+appoint"%(formatted_date,index,statusCode,teacherObj['nickname']))
        ])
    hideRestButtonText='显示' if studentObj['hideRest'] else "隐藏"
    keyboard.append([
            InlineKeyboardButton(text='%s休息时段'%hideRestButtonText,callback_data='%s+hideRest_STD'%teacherObj['nickname']),
            InlineKeyboardButton('直连%s'%teacherObj['nickname'],url="https://t.me/%s"%(teacherObj['nickname'])),#
            InlineKeyboardButton(text='今/明天课表',callback_data='today/tomorrow+student+%s'%teacherObj['nickname'])
            ])
    keyboard.append([
            InlineKeyboardButton(text='刷新课表',callback_data='%s+STD_refresh'%teacherObj['nickname']),
            InlineKeyboardButton(text='我的预约',callback_data='STD_mycourse'),
            ])
    return InlineKeyboardMarkup(keyboard)

def moreSetBotton(teacherObj,date,peroidIndex,statusCode):
    '''更多功能设置'''
    keyboard=[]
    if statusCode==3:#已经确认
        tempList=list(filter(lambda item: item['date']==date and item['peroidIndex']==int(peroidIndex),teacherObj['bookedCourseList']))
        if len(tempList)==1:
            stu=tempList[0]
            keyboard.append([
                InlineKeyboardButton(text='取消已预约课程',callback_data='%s %s %s+moreSet'%(date,peroidIndex,stu['nickname'])),
            ])

        
    return InlineKeyboardMarkup(keyboard)
def createMarkupConfirmOne(studentAptList,date,peroidIndex):
    '''用于老师从多个预约中选择一个学生'''
    keyboard=[]
    for stu in studentAptList:
        keyboard.append([
                InlineKeyboardButton(stu['fullname'],url="https://t.me/%s"%(stu['nickname'])),
                InlineKeyboardButton(text='确认申请',callback_data='%s %s %s+ConfirmOne'%(date,peroidIndex,stu['nickname'])),
                InlineKeyboardButton(text='拒绝',callback_data='%s %s %s+Reject'%(date,peroidIndex,stu['nickname'])),
                ])
    return InlineKeyboardMarkup(keyboard)

def studentCourse(studentObj,SQLres):
    '''一个学生的多个预约管理，取消申请功能'''
    keyboard=[]
    for row in SQLres:
        teacher,student,date,peroidIndex,status,_,id=row
        if int(status)==0 or int(status)==1:
            keyboard.append([
                    InlineKeyboardButton('%s %s'%(date,time_intervals[peroidIndex]),url="https://t.me/%s"%(teacher)),
                    InlineKeyboardButton('@%s'%(teacher),url="https://t.me/%s"%(teacher)),
                    InlineKeyboardButton(text='取消申请',callback_data='%s %s %s %s %s+stuCancelOne'%(teacher,student,date,peroidIndex,id)),
                    ])
    return InlineKeyboardMarkup(keyboard)
    
def cancelOneButton(courseID):
    '''用于老师取消一个已确认的预约'''
    keyboard=[]
    keyboard.append([
            InlineKeyboardButton(text='取消预约',callback_data='%s+teaCancelChecked'%(courseID)),
            ])
    return InlineKeyboardMarkup(keyboard)



